package com.fw.ui.view.event;

/*
 * #%L
 * Vaadin 7 Spring Security Integration
 * %%
 * Copyright (C) 2012 Nicolas Fr�nkel
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.fw.ui.core.SpringViewProvider;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;

@org.springframework.stereotype.Component
@Scope(SCOPE_PROTOTYPE)
public class ViewChangeEventListener implements ViewChangeListener {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public static final String ATT_CONFIRM_CHANGE_VIEW = "ATT_CONFIRM_CHANGE_VIEW";
    public static final String ATT_NO_CONFIRM_CHANGE_VIEW = "ATT_NO_CONFIRM_CHANGE_VIEW";

    private View currentView;
    private String currentViewName;

    @Override
    public boolean beforeViewChange(ViewChangeEvent event) {

	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

	SpringViewProvider securityViewProvider = (SpringViewProvider) SpringViewProvider
		.createViewProvider((Authentication) authentication);

	View view = securityViewProvider.getView(event.getViewName());
	if (view == null) {
	    return false;
	}

//	if (event.getNewView().equals(event.getOldView())) {
//	    return false;
//	}

	return authentication == null ? false : authentication.isAuthenticated();

    }

    @Override
    public void afterViewChange(ViewChangeEvent event) {
	this.currentView = event.getNewView();
	this.currentViewName = event.getViewName();
    }

    public View getCurrentView() {
	return this.currentView;
    }

    public String getCurrentViewName() {
	return this.currentViewName;
    }

}
